import React from 'react';
import {fabric} from 'fabric';

import {CanvasPopupMenu} from './canvasPopupMenu.jsx';
import {DrawHandler} from './canvasWorker/index';

class CanvasContainer extends React.Component {
    refs = {
        canvas: null
    };
    state = {
        isShowPopupMenu: false,
        popupPointer: [0, 0]
    };
    canvas = null;
    _drawingBoard = null;
    
    constructor(props) {
        super(props);
    }

    /**
     * 处理resize
     */
    handleResize = (e) => {
        const dom = this.refs.canvas.parentElement.parentElement;
        this.canvas.setWidth(dom.clientWidth);
        this.canvas.setHeight(dom.clientHeight);
    }

    componentDidMount = () => {
        fabric.Object.prototype.objectCaching = false;
		fabric.Object.prototype.statefullCache = true;
        this.canvas = new fabric.Canvas(this.props.canvasId);
        this._drawingBoard = new DrawHandler(this.canvas);
        this.props.onBuildDrawingBorad(this._drawingBoard);
        

        window.addEventListener('resize', this.handleResize);
        this.handleResize();
    }

    componentWillUnmount = () => {
        window.removeEventListener('resize', this.handleResize);
    }

    onClick =(e) => {
        this.setState({
            isShowPopupMenu: false
        });
    }

    /**
     * 显示右键菜单
     */
    onContextMenu = (e) => {
        e.preventDefault();
        let offsetX = e.nativeEvent.clientX - e.currentTarget.offsetLeft;
        let offsetY = e.nativeEvent.clientY - e.currentTarget.offsetTop;
        this.setState({
            isShowPopupMenu: true,
            popupPointer: [offsetX, offsetY]
        });
    }

    /**
     * 更新位置
     */
    onPopupMenuUpdate = (dom) => {
        const parentDom = this.refs.canvas.parentElement.parentElement;
        let offsetLeft = this.state.popupPointer[0];
        let offsetTop = this.state.popupPointer[1];
        let isRefreash = false;
        if (dom.clientWidth + dom.offsetLeft > parentDom.clientWidth) {
            offsetLeft -= dom.clientWidth;
            isRefreash = true;
        }

        if (dom.clientHeight + dom.offsetTop > parentDom.clientHeight) {
            offsetTop -= dom.clientHeight;
            isRefreash = true;
        }

        if (isRefreash) {
            this.setState({
                popupPointer: [offsetLeft, offsetTop]
            });
        }
    }

    render() {
        return (
            <div style={{width: '100%', height: '100%', position: 'relative'}} onClick={this.onClick} onContextMenu={this.onContextMenu}>
                <canvas style={{width: '100%', height: '100%'}} id={this.props.canvasId} ref={dom => {this.refs.canvas = dom;}}/>
                {this.state.isShowPopupMenu && <CanvasPopupMenu pointer={this.state.popupPointer} onUpdate={this.onPopupMenuUpdate} />}
            </div>
        );
    }
}

export {CanvasContainer};